package com.xlf.common.core.util;

import org.apache.commons.codec.binary.Hex;

import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.function.Predicate;

/**
 * 文件工具类
 */
public class FileUtil {

    /**
     * 将多个文本文件合并为一个文本文件
     *
     * @param outFileName
     * @param inFileNames
     * @throws IOException
     */
    public static void merge(String outFileName, List<String> inFileNames) throws IOException {
        FileWriter writer = new FileWriter(outFileName, false);
        for (String inFileName : inFileNames) {
            System.out.println();
            try {
                String txt = readToString(inFileName);
                writer.write(txt);
                System.out.println(txt);
            } catch (Exception e) {
            }
        }
        writer.close();
    }

    /**
     * 查找某目录下的所有文件名称
     *
     * @param path
     * @return
     */
    public static List<String> getFiles(String path) {
        List<String> files = new ArrayList<String>();
        File file = new File(path);
        File[] tempList = file.listFiles();
        for (int i = 0; i < tempList.length; i++) {
            if (tempList[i].isFile()) { //如果是文件
                files.add(tempList[i].toString());
            }
            if (tempList[i].isDirectory()) {    //如果是文件夹
                files.addAll(getFiles(tempList[i].toString()));
            }
        }
        return files;
    }

    /**
     * 读取文本文件内容到字符串
     *
     * @param fileName
     * @return
     * @throws IOException
     */
    public static String readToString(String fileName) throws IOException {
//        String encoding = "UTF‐8";
        File file = new File(fileName);
        Long filelength = file.length();
        byte[] filecontent = new byte[filelength.intValue()];
        FileInputStream in = new FileInputStream(file);
        in.read(filecontent);
        in.close();
//        return new String(filecontent, encoding);
        return new String(filecontent, StandardCharsets.UTF_8);
    }

    /**
     * 获取文件md5值
     *
     * @param inputStream 文件输入流
     * @return {@link String} 文件md5值
     */
    public static String getMd5(InputStream inputStream) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("md5");
            byte[] buffer = new byte[8192];
            int length;
            while ((length = inputStream.read(buffer)) != -1) {
                md5.update(buffer, 0, length);
            }
            return new String(Hex.encodeHex(md5.digest()));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 得到文件扩展名,得不到返回文件本身 eg: 2005.jpg => jpg eg 2005 => 2005
     *
     * @param fileName 文件名称
     * @return {@link String} 文件后缀
     */
    public static String getExtName(String fileName) {
        if (StringUtils.isEmpty(fileName)) {
            return "";
        }
        return fileName.substring(fileName.lastIndexOf(".")+1);
    }

    /**
     * 得到文件扩展名,得不到返回空串  2005.jpg =>jpg eg 2005 => ""
     *
     * @param fileName 文件名称
     * @return {@link String} 文件后缀
     */
    public static String getExtNameTo(String fileName) {
        if (StringUtils.isEmpty(fileName)) {
            return "";
        }
        int i = fileName.lastIndexOf(".");
        if(i==-1)
            return "";
        return fileName.substring(i+1);
    }



    /**
     * 获得去除后缀的文件名 eg：xxx.jsp=>xxx eg: xxx=>xxx
     * @param fileName
     * @return
     */
    public static String getFileName(String fileName){
        if (StringUtils.isEmpty(fileName)) {
            return "";
        }
        int i = fileName.lastIndexOf(".");
        if(i==-1)
            return fileName;
        String substring = fileName.substring(0,i);
        return substring;
    }

    /**
     * 文件名加后缀，eg abc.jpg => abc(k).jpg eg: abc => abc(k)
     *
     * @param name 文件名
     * @param  k 后缀
     * @return
     */
    public static String fileNameAddSuffix(String name,int k){

        //获取扩展名，没有扩展名返回文件本身
        String ExtName = getExtName(name);
        //去除扩展名
        String FileName = getFileName(name);
        //后缀
        String kk =String.valueOf(k);
        //没有扩展名直接加后缀
        if(ExtName.equals(name)){
            return name+'('+kk+')';
        }else {
            return FileName+'('+kk+')'+'.'+ExtName;
        }
    }

    /**
     * 解决文件命名冲突
     * @param name 文件名 eg: xxxx.jpg xxxx.mp4  xxxx
     * @param isConflict 断言函数式接口，判断新的文件名是否冲突
     * @return
     */
    public static String addSuffix(String name, Predicate<String> isConflict) {
        String newName = name;
        int k=1;
        while (true){
            //不冲突
            if(isConflict.test(newName)==false)
                break;
            newName = fileNameAddSuffix(name,k);
            ++k;
        }
        return newName;
    }

    /**
     * 转换file
     *
     * @param multipartFile 多部分文件
     * @return {@link File} file
     */
    public static File multipartFileToFile(MultipartFile multipartFile) {
        File file = null;
        try {
            String originalFilename = multipartFile.getOriginalFilename();
            String[] filename = Objects.requireNonNull(originalFilename).split("\\.");
            file = File.createTempFile(filename[0], filename[1]);
            multipartFile.transferTo(file);
            file.deleteOnExit();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }





}
